//
//  ViewController.m
//  LSYReader
//
//  Created by Labanotation on 16/5/30.
//  Copyright © 2016年 okwei. All rights reserved.
//
#import "UIColor+EV.h"
#import "EVAlertView.h"
#import "EVEmptyView.h"
#import "ViewController.h"
#import "LSYReadViewController.h"
#import "LSYReadPageViewController.h"

#import "UIImageView+WebCache.h"
#import "LSYNetBookController.h"

#import "LSYReadUtilites.h"
#import "LSYReadModel.h"
#import "LSYNovelService.h"
#import "LSYFileUtil.h"
#import "LSYBookManager.h"
#import "HTKSampleCollectionViewCell.h"
@interface ViewController () {
    BOOL _isEditing;
}
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ViewController

- (instancetype)init {
    self = [super init];
    if (self) {
//        [self getNovel:nil];
        [self setup];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self =[super initWithCoder:aDecoder]) {
//        [self getNovel:nil];
        [self setup];
    }
    return self;
}

- (NSMutableArray *)dataArray {
    return [[LSYBookManager manager] books];
}

- (void)setup {
    // basic setup
    self.title = @"爱看阅读";
    // Add button that will "add" item to demo
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBooks:)];
    [self reloadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBooks:) name:kBookManagerRefresBooksNoti object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [self reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Register cell
    // If you are using Storyboards/Nibs, make sure you "registerNib:" instead.
    [self.collectionView registerNib:[UINib nibWithNibName:@"HTKSampleCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HTKSampleCollectionViewCell"];

    // Setup item size
    HTKDragAndDropCollectionViewLayout *flowLayout = (HTKDragAndDropCollectionViewLayout *)self.collectionView.collectionViewLayout;
    CGFloat itemWidth   = (self.collectionView.bounds.size.width - 80)/3.0;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth*1.3 + 38);
    flowLayout.minimumInteritemSpacing = 20;
    flowLayout.lineSpacing = 20;
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    self.collectionView.backgroundColor = [UIColor ev_colorWithHex:0xF0F0F0];
}

#pragma mark - User Actions

- (void)searchBooks:(id)sender {
    LSYNetBookController *controller = [[LSYNetBookController alloc] initWithNibName:@"LSYNetBookController" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)editBook:(id)sender {
    _isEditing = !_isEditing;
    [self reloadData];
}

- (void)refreshBooks:(NSNotification *)aNoti {
    [self reloadData];
}

- (void)reloadData {
    [self.collectionView reloadData];
    if (self.dataArray.count>0) {
        [self hideEmptyView];
    } else {
        [self ev_showEmptyViewForType:EVEmptyViewOrder title:@"点击搜索书籍"];
    }
}

#pragma mark emptyView onEmptyViewResponded
- (void)onEmptyViewResponded {
    [self searchBooks:nil];
}

#pragma mark - UICollectionView Datasource/Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HTKSampleCollectionViewCell *cell = (HTKSampleCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:HTKDraggableCollectionViewCellIdentifier forIndexPath:indexPath];
    // Set number on cell
    LSYReadModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    // Set our delegate for dragging
    cell.draggingDelegate = self;
    cell.editing = _isEditing;
    return cell;
}

#pragma mark - HTKDraggableCollectionViewCellDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LSYReadModel *model = self.dataArray[indexPath.row];
    NSLog(@"%@",model.title);
    LSYReadPageViewController *pageController = [[LSYReadPageViewController alloc] init];
    pageController.model = model;
    [self presentViewController:pageController animated:YES completion:^{
        [[LSYBookManager manager] refreshBook:model];
    }];
}

- (BOOL)userCanDragCell:(UICollectionViewCell *)cell {
    // All cells can be dragged in this demo
    return !_isEditing;
}

- (void)userDidEndDraggingCell:(UICollectionViewCell *)cell {
    
    HTKDragAndDropCollectionViewLayout *flowLayout = (HTKDragAndDropCollectionViewLayout *)self.collectionView.collectionViewLayout;
    
    // Save our dragging changes if needed
    if (flowLayout.finalIndexPath != nil) {
        // Update datasource
        NSObject *objectToMove = [self.dataArray objectAtIndex:flowLayout.draggedIndexPath.row];
        [self.dataArray removeObjectAtIndex:flowLayout.draggedIndexPath.row];
        [self.dataArray insertObject:objectToMove atIndex:flowLayout.finalIndexPath.row];
    }
    
    // Reset
    [flowLayout resetDragging];
}

- (void)deleteCell:(UICollectionViewCell *)cell obj:(id)obj {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    LSYReadModel *book = [self.dataArray objectAtIndex:indexPath.row];
    NSLog(@"%@",book.title);
    [EVAlertView showMessageAlertView:@"是否确定删除？" commitButton:@"删除" cancelButton:@"取消" dismissBlock:^(EVAlertViewStruct result) {
        if (result.buttonIndex == EVAlertViewButtonIndexCommit) {
            [[LSYBookManager manager] removeBook:book];
        }
    }];
}

- (void)longPressCell:(UICollectionView *)cell {
    [self editBook:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
